package com.serkol.ams.module.base;


import cn.hutool.core.bean.BeanUtil;
import com.serkol.ams.module.sys.entity.SysMenu;
import com.serkol.ams.module.sys.entity.SysUsers;
import com.serkol.ams.module.sys.valid.LoginParams;
import com.serkol.ams.utils.JwtUtils;
import com.serkol.ams.utils.R;
import com.serkol.ams.utils.RedisUtil;
import com.serkol.ams.vo.UserLoginVo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;


@RestController
public class LoginController {

    @Autowired(required = false)
    AuthenticationManager authenticationManager;
    @Resource
    private RedisUtil redisUtil;
    @PostMapping("/login")
    public R doLogin(@RequestBody @Valid LoginParams loginParams) {
        //user.setPassword("123456");
        System.out.println("doLogin");
        //System.out.println("passwordEncoder.encode(user.getPassword()) = " + passwordEncoder.encode(user.getPassword()));
        System.out.println(loginParams);
        UsernamePasswordAuthenticationToken unauthenticated = UsernamePasswordAuthenticationToken.unauthenticated(loginParams.getUsername(), loginParams.getPassword());
        try {
            Authentication authenticate = authenticationManager.authenticate(unauthenticated);
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            SysUsers principal =(SysUsers) authenticate.getPrincipal();
            System.out.println(principal);

            return getToken(principal);//jwtTokenService.generateToken(authenticate.getName(), null);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return R.error();
        }
    }
    @GetMapping("/")
    public String index() {
        return "index";
    }

    private R getToken(SysUsers one){
                List<SysMenu> permissionList = one.getPermissionList();
        //筛选当前用户权限拥有的菜单数据
        List<String> collect = permissionList.stream()
                // 0 目录 1菜单
                //只筛选目录与菜单数据，按钮不需要加到路由中
                .map(SysMenu::getCode).collect(Collectors.toList());
                 UserLoginVo userLoginVo = new UserLoginVo();
                    BeanUtil.copyProperties(one, userLoginVo);
                    userLoginVo.setRoles(collect);
                    //生成token
                    String token = JwtUtils.getJwtToken(one.getId()+"",one.getUsername());
                    userLoginVo.setToken(token);
                    //将token信息保存到Redis中
                    String tokenKey = "token_"+token;
                    redisUtil.set(tokenKey, token,18000);
                    /**
                     * 数据放入到redis中  30分钟过期
                     */
                    redisUtil.set(one.getUsername()+"_"+one.getId(),userLoginVo,18000);
                    return  R.ok("登录成功!").put("data", userLoginVo);
    }
}
